﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;
using OxyPlot;

namespace PlayOxyPlot
{
    public sealed class DateValue
    {
        public DateTime Time { get; private set; }
        public double Value { get; private set; }
        public int Index { get; private set; }

        public DateValue(DateTime dt,double value,int index)
        {
            this.Time = dt;
            this.Value = value;
            this.Index = index;
        }
    }

    public partial class DynamicSimulationView : UserControl
    {
        private readonly DispatcherTimer _timer;
        private readonly Queue<DateValue> _dateValues;

        public DynamicSimulationView()
        {
            InitializeComponent();
            _dateValues = new Queue<DateValue>();

            var model = new PlotModel();
            model.Axes.Add(new LinearAxis(AxisPosition.Left, -2, 2));

            var xaxis = new DateTimeAxis(AxisPosition.Bottom, "Time", "mm:ss", DateTimeIntervalType.Seconds);
            //!!! below codes no effect 
            //xaxis.MinorStep = 1;
            //xaxis.MinorIntervalType = DateTimeIntervalType.Seconds;

            model.Axes.Add(xaxis);

            model.Series.Add(new LineSeries
            {
                ItemsSource = _dateValues,
                DataFieldX = "Time",
                DataFieldY = "Value",
                Color = OxyColors.Navy,
                MarkerSize = 5,
                MarkerStroke = OxyColors.Orange,
                MarkerFill = OxyColors.Orange,
                MarkerType = MarkerType.Triangle
            });
            plot.Model = model;

            _timer = new DispatcherTimer {Interval = TimeSpan.FromSeconds(0.333333)};
            _timer.Tick += OnTicked;
            _timer.Start();
        }

        void OnTicked(object sender, EventArgs e)
        {
            int index = _dateValues.Count > 0 ? _dateValues.Last().Index + 1 : 0;
            if (_dateValues.Count >= 120)
                _dateValues.Dequeue();
            double y = 0;
            const int m = 80;
            for (int j = 0; j < m; j++)
                y += Math.Cos(0.001 * index * j * j);
            y /= m;
            _dateValues.Enqueue(new DateValue(DateTime.Now,y,index));

            plot.RefreshPlot(true);
        }
    }
}
